package com.gator.rocketmq.producer;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * @Author PABLO
 * @Date 2022/6/7 19:21
 * @Desc 同步发送生产者
 */
public class Producer {
    public static void main(String[] args) throws MQClientException, InterruptedException {

        DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");

        producer.setNamesrvAddr("localhost:9876");
        producer.start();
     /*   //同步发送
        for (int i = 0; i < 10; i++  )
            try {
                {
                    Message msg = new Message("TopicTest",
                            "TagA",
                            "OrderID188",
                            "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                    SendResult sendResult = producer.send(msg);
                    System.out.printf("%s%n", sendResult);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }*/
        //异步
        for (int i = 0; i < 10; i++)
            try {
                {
                    Message msg = new Message("TopicTest",
                            "TagA",
                            "OrderID188",
                            "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                    producer.send(msg, new SendCallback() {
                        //发送成功
                        @Override
                        public void onSuccess(SendResult sendResult) {
                            System.out.printf("%s%n", sendResult);
                        }
                        //发送失败
                        @Override
                        public void onException(Throwable e) {
                            System.out.println(e.getMessage());
                            e.printStackTrace();
                        }
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        //单向
    /*    for (int i = 0; i < 10; i++)
            try {
                {
                    Message msg = new Message("TopicTest",
                            "TagA",
                            "OrderID188",
                            ("Hello world" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                    producer.sendOneway(msg);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }*/


        //producer.shutdown();
    }

}
